import { axios } from 'taro-axios'
import Taro from '@tarojs/taro'
import { getToken } from 'tools'
import { BASE_URL } from 'tools/constant'
const HTTP = axios.create({
  timeout: 30000,
  baseURL: BASE_URL
})
HTTP.interceptors.request.use(
  request => {
    let token = getToken()
    if (token) {
      request.headers.Authorization = `bearer ${token}`
    }
    return request
  },
  error => {
    console.log(error)
  }
)

HTTP.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response.data
    }
  },
  error => {
    const currentRoute = Taro.getCurrentPages()[0].route
    const loginPath = 'pages/login/index'
    if (error.toString().includes('401') && loginPath !== currentRoute) {
      Taro.navigateTo({
        url: `/${loginPath}`
      })
    }
    throw error
  }
)
const createAxios = () => {
  return axios.create()
}
export { createAxios, HTTP }
